package cn.example.vip.mall.goods.controller;

import cn.example.vip.mall.goods.entity.Category;
import cn.example.vip.mall.goods.service.CategoryService;
import cn.example.vip.mall.util.RespResult;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@CrossOrigin	// 生产环境需要去掉
@RestController
@RequestMapping("/category")
public class CategoryController {
	@Autowired
	CategoryService categoryService;
	
	/**
	 * 根据 parentId
	 * parentId = 0 ? 顶级分类 : 多级分类
	 * @param parentId
	 * @return
	 */
	@GetMapping("/parent/{parentId}")
	public RespResult findByParentId(@PathVariable("parentId") Integer parentId) {
		return RespResult.ok(categoryService.findByParentId(parentId));
	}
	
	/**
	 * 根据分类ID查询分类信息
	 */
	@GetMapping("/{id}")
	public RespResult findById(@PathVariable("id") Integer id) {
		return RespResult.ok(categoryService.getById(id));
	}
	
	/**
	 * 查找 相似的全部品牌
	 */
	@PostMapping("/search")
	public RespResult<List<Category>> search(@RequestBody Category category) {
		List<Category> categoryList = categoryService.queryList(category);
		return RespResult.ok(categoryList);
	}
	
	/**
	 * 分页查找 相似的全部品牌
	 */
	@PostMapping("/search/{page}/{size}")
	public RespResult<List<Category>> search(@RequestBody Category category,
											 @PathVariable Long page,
											 @PathVariable Long size) {
		Page<Category> categoryPageList = categoryService.queryPageList(category, page, size);
		return RespResult.ok(categoryPageList);
	}
	
	/**
	 * 添加 品牌
	 */
	@PostMapping("/add")
	public RespResult add(@RequestBody Category category) {
		if(categoryService.save(category)){
			return RespResult.ok();
		}else {
			return RespResult.error();
		}
	}
	
	/**
	 * 根据id 更新 品牌
	 */
	@PostMapping("/update")
	public RespResult update(@RequestBody Category category) {
		if(categoryService.updateById(category)){
			return RespResult.ok();
		}else{
			return RespResult.error();
		}
	}
	
	/**
	 * 根据id 删除 品牌
	 */
	@DeleteMapping("/{id}")
	public RespResult delete(@PathVariable("id") Long id) {
		if(categoryService.removeById(id)){
			return RespResult.ok();
		}else {
			return RespResult.error();
		}
	}

}
